package com.gps.pe.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.gps.pe.base.api.AbstractPlacementEngineController;
import com.gps.pe.exception.PeException;
import com.gps.pe.model.User;
import com.gps.pe.service.IUserService;
import com.gps.pe.service.UserService;
import com.gps.pe.utility.GlobalConstantEnum;
import com.gps.pe.utility.StringUtils;

/**
 * JobSeerker Login controller class
 * 
 * @author GPS
 *
 */
public class JobSeekerLoginController extends AbstractPlacementEngineController {
	private static final Logger LOGGER = Logger.getLogger(JobSeekerLoginController.class);

	@Override
	public void execute(HttpServletRequest req, HttpServletResponse resp) throws PeException {
		LOGGER.debug("Job Seeker Login  Controller execution started...");

		String username = req.getParameter("username").trim();
		String password = req.getParameter("password").trim();

		if (StringUtils.isStringEmpty(username) || StringUtils.isStringEmpty(password)) {
			req.setAttribute("errorMsg", "Username / Password is empty...");
			LOGGER.info("Login / Password is empty...");
		} else if (validateUser(username, password)) {
			LOGGER.info("User [ " + username + "] validated ...");
		} else {
			req.setAttribute("errorMsg", "Invalid Username / Password...");
			LOGGER.info("Invalid Username / Password...");
		}
	}

	@Override
	public final String resolveView(HttpServletRequest req, HttpServletResponse resp) throws PeException {
		LOGGER.debug("Job Seeker Login  Controller called...");

		if (!StringUtils.isStringEmpty((String) req.getAttribute("errorMsg"))) {
			req.setAttribute("centerPageAtrributeHandler", "jobSeekerLogin");
			req.setAttribute("pageIdentifier", "jobSeekerLogin");
		} else {
			// Move to next page - Job seekers page
		}
		return "jsp/placementengine.jsp";
	}

	/**
	 * This method validates the user
	 * 
	 * @return
	 */
	private boolean validateUser(String username, String password) {
		LOGGER.debug("Validating user [" + username + "]");
		IUserService userService = new UserService();
		User user = userService.getUserByLoginId(username);
		return (user != null && user.getPassword().equals(password)) ? true : false;
	}
}
